<?php
include 'connect_db.php';
if (!checkLoggedin())
{
  header('Location: login.php');
}

$err = ' ';

if ( isset($_POST['submit'])
  && isset($_POST['house_name'])
  && isset($_POST['house_address'])
  && $_POST['house_name'] != null
  && $_POST['house_address'] != null )
{
  $house_name = $_POST['house_name'];
  $house_address = $_POST['house_address'];

  $sql = "INSERT INTO Houses (name, address) VALUES ('" . $house_name  . "', '" . $house_address  . "')";
  $result = mysql_query($sql);
  
  $sql = "SELECT id FROM Houses ORDER BY id DESC LIMIT 1";
  //$sql = "SELECT LAST(id) FROM Houses";
  $result = mysql_query($sql);
  $row = mysql_fetch_row($result);
  
  $sql = "INSERT INTO houses_users ( house_id, user_id, privilege ) VALUES ('" . $row[0] . "', '" . $_SESSION['id'] . "', 1)";
  $result = mysql_query($sql);

  
  $sql = "SELECT house_id FROM Houses WHERE name=" . $house_name . "', house_address='" . $house_address . "')";
  $result = mysql_query($sql);
  
  header('Location: index.php');
}
/*check if all fields are completed*/
else if ( isset($_POST['submit'])
       && isset($_POST['house_name'])
       && isset($_POST['house_address'])
       && ($_POST['house_name'] == null || $_POST['house_address'] == null ))
{
  $err = 'Please complete all fields.';
}

?>

<?php include('templates/main/header.php'); ?>

<div id="body">
  <div id="content" class="right_sidebar">
	<div id="createhouse">
	  <hr>
	  <h1>Create a Household</h1>
	  <hr>
	  <br />
	  <br />
	  <form name="input" action="createhouse.php" method="POST">
    <?php if ($err != ' ') { ?>
    <div class="errors">
      <p><?php echo $err; ?></p>
    </div>
    <?php } ?>
    <div class="errors clear"></div>      
		<h3>House Name*:</h3> <input type="text" name="house_name">
		<h3>House Address*:</h3> <input type="text" name="house_address">
		<input type="submit" value="Create House" name="submit">
	  </form>
	</div>
  </div>
</div>
 
<?php include('templates/main/footer.php'); ?>